
export default {
  host: window.projectConfig.host,
  ajax (obj) {
    if (!obj.url) {
      console.error('arguments must have a url!')
    }

    obj.url = this.host + obj.url
    obj.method = (obj.method || 'get').toUpperCase()
    obj.data = obj.data || {}

    if (obj.method === 'GET' || obj.method === 'DELETE') {
      obj.url += this.obj2query(obj.data)
    }

    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          if (xhr.status < 400) {
            try {
              let resJson = JSON.parse(xhr.responseText)
              resolve(resJson)
            } catch {
              reject(xhr)
            }
          } else {
            reject(xhr)
          }
        }
      }

      xhr.open(obj.method, obj.url, true)
      // xhr.setRequestHeader('Content-Type', 'application/json')

      if (obj.method === 'POST' || obj.method === 'PUT') {
        let fd = new FormData()
        for (let key in obj.data) {
          fd.append(key, obj.data[key])
        }
        xhr.send(fd)
      } else {
        xhr.send(null)
      }
    })
  },
  get (url, obj) {
    let sendObj = {
      method: 'GET',
      url: url
    }

    if (typeof obj !== 'undefined') {
      sendObj.data = obj
    }

    return this.ajax(sendObj)
  },
  post (url, obj) {
    let sendObj = {
      method: 'POST',
      url: url
    }
    if (typeof obj !== 'undefined') {
      sendObj.data = obj
    }

    return this.ajax(sendObj)
  },
  put (url, obj) {
    let sendObj = {
      method: 'PUT',
      url: url
    }
    if (typeof obj !== 'undefined') {
      sendObj.data = obj
    }

    return this.ajax(sendObj)
  },
  // default
  getQuery (key) {
    let searchStr = window.location.search
    let resObj = {}
    if (searchStr) {
      searchStr = searchStr.replace('?', '')
      let searchArr = searchStr.split('&')
      for (let item of searchArr) {
        let itemArr = item.split('=')
        resObj[itemArr[0]] = itemArr[1]
      }

      if (key) {
        return resObj[key]
      } else {
        return resObj
      }
    } else {
      return null
    }
  },
  obj2query (obj) {
    let res = '?'
    for (let key in obj) {
      res += key.toString() + '=' + obj[key].toString() + '&'
    }
    res = res.substr(0, res.length - 1)
    return res
  },
  // 清空对象的null
  clearObj (obj) {
    dp(obj)
    return obj

    function dp (obj) {
      for (let key in obj) {
        if (obj[key] === null || (typeof obj[key] === 'undefined')) {
          delete obj[key]
        }

        if (typeof obj[key] === 'object') {
          dp(obj[key])
        }
      }
    }
  }
}
